<template>
  <a-modal
    :title="title"
    centered
    :width="980"
    :maskClosable="false"
    :destroyOnClose="true"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="cancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :model="form" ref="formRef" :rules="formRules">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item
              label="职位名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="name"
              :rules="[{ required: true,  message: '请输入职位名称！' }]"
            >
              <a-input :maxLength="35" placeholder="请输入职位名称" v-model:value="form.name" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item 
            label="唯一编码"
             :labelCol="labelCol" 
             :wrapperCol="wrapperCol"
              has-feedback
              name="code"
             :rules="[{ required: true,  message: '请输入唯一编码！' }]"
             >
              <a-input :maxLength="35" placeholder="请输入昵称" v-model:value="form.code" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item
              label="排序"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="sort"
              :rules="[{ required: true,  message: '请输入排序！' }]"
            >
              <a-input-number :min="0" :max="1000"  placeholder="请输入排序" v-model:value="form.sort" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item
              label="备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              name="remark"
            >
              <a-textarea :maxLength="100" placeholder="请输入备注" v-model:value="form.remark">
                
              </a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, toRefs, ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { formRules } from '@/utils/validator'
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { sysPosList, sysPosAdd, sysPosEdit } from '@/api/system/pos'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { uniqueId } from 'lodash'
interface extIdsType {
  key: string
  orgId: unknown
  posId: unknown
}
export default defineComponent({
  name: 'posFrom',
  components: {},
  props: {
    treeData: {
      type: Array,
      default: []
    },
    title: {
      type: String,
      default: ''
    }
  },
  emits: ['refresh'],
  setup(props, ctx) {
    const formRef = ref<any>(null)
    const router = useRouter()
    const store = useStore()
    const state = reactive({
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 机构行样式
      labelCol_JG: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol_JG: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      count: 1,
      add: false,
      visible: false,
      confirmLoading: false,
      orgList: [] as any,
      posList: [],
      detailData: {} as any,
      sysEmpParamExtList: [],
      memberLoading: false,
      form: {
        id:'',
        name:'',
        code:'',
        remark:'',
        sort:100
      },
      birthdayString: [] as string[]
    })
    /**详情监听 */
    watch(
      () => state.detailData,
      (v) => {
        var posIdList = [] as string[]
        var extIds = [] as extIdsType[]
         console.log(v)
        // v.sysEmpInfo.positions.map((v) => {
        //   posIdList.push(v.posId)
        // })
        // v.sysEmpInfo.extOrgPos.map((vv, i) => {
        //   extIds.push({
        //     key: uniqueId(),
        //     orgId: vv.orgId,
        //     posId: vv.posId
        //   })
        // })
        state.form = {
          name:v.name,
          id:v.id,
          code:v.code,
          sort:v.sort,
          remark:v.remark
        }
      }
    )
    onMounted(() => {
      sysPosList({}).then((res) => {
        state.posList = res
      })
      // getOrgList().then((res) => {
      //   state.orgList = res
      // })
    })
    function handleSubmit() {
      state.confirmLoading = true
      console.log(props.title)
      if(props.title=='新增职位'){
        formRef.value
          .validate()
          .then(() => {
            sysPosAdd(state.form)
              .then(res => {
                console.log(res)
                  message.success('新增成功')
                  state.confirmLoading = false
                  state.visible = false
                  ctx.emit('refresh')
                  resetForm()
                
              })
              .catch((err) => {
                state.confirmLoading = false
              })
          })
          .catch((err) => {
            state.confirmLoading = false
            console.log('nopass', err)
          })
      }else {
        formRef.value
          .validate()
          .then(() => {
            sysPosEdit(state.form)
              .then((res) => {
                  message.success('编辑成功')
                  state.confirmLoading = false
                  state.visible = false
                  ctx.emit('refresh')
                  resetForm()
                
              })
              .catch((err) => {
                state.confirmLoading = false
              })
          })
          .catch((err) => {
            state.confirmLoading = false
            console.log('nopass', err)
          })
      }
    }
    /**
     * 重置表单
     */
    function resetForm() {
      state.form = {
        account: '',
        name: '',
        nickName: '',
        confirm: '',
        password: '',
        phone: '',
        email: '',
        birthday: '',
        sex: 1,
        sysEmpParam: {
          extIds: [] as extIdsType[],
          orgId: undefined,
          orgName: '',
          posIdList: []
        }
      }
    }
    /**
     * 退出
     */
    const cancel = () => {
      resetForm()
      //   formRef.value.resetFields()
      state.visible = false
      state.detailData={}
    }
    /**
     * 禁用日期
     */
    const disabledDate = (current) => {
      return current && current > dayjs().endOf('day') //当天之前的不可选，包括当天
      // return current < dayjs().subtract(1, 'day')// 当天之前的不可选，不包括当天
    }

    /**
     * 增行
     */
    function newMember() {
      let data = state.form.sysEmpParam.extIds
      let length = data.length
      data.push({
        key: uniqueId(),
        orgId: undefined,
        posId: undefined
      })
    }
    /**
     * 删除
     */
    function remove(key) {
      state.form.sysEmpParam.extIds.splice(
        state.form.sysEmpParam.extIds.findIndex((v) => v.key == key),
        1
      )
    }
    /**
     * handleChange
     */
    function handleChange() {}
    /**
     * 选择树机构，初始化机构名称于表单中
     */
    function initrOrgName(value, label, extra) {
      console.log('vv', value, label, extra)
      state.form.sysEmpParam.orgId = value
      state.form.sysEmpParam.orgName = label[0]
    }
    const validatePass = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请输入密码')
      } else {
        if (state.form.confirm !== '') {
          formRef.value.validateField('checkPass')
        }
        return Promise.resolve()
      }
    }
    const validatePass2 = async (rule: RuleObject, value: string) => {
      if (value === '') {
        return Promise.reject('请再次输入密码')
      } else if (value !== state.form.password) {
        return Promise.reject('请确认两次输入密码的一致性！')
      } else {
        return Promise.resolve()
      }
    }
    return {
      ...toRefs(state),
      props,
      formRef,
      formRules,
      handleSubmit,
      initrOrgName,
      validatePass,
      validatePass2,
      handleChange,
      disabledDate,
      cancel,
      remove,
      newMember
    }
  }
})
</script>
<style scoped lang="scss">
  .ant-input-number{
    width: 100%;
  }
</style>
